package cn.wolfcode.shop.cloud.service.impl;

import cn.wolfcode.shop.cloud.common.JSONUtil;
import cn.wolfcode.shop.cloud.domain.User;
import cn.wolfcode.shop.cloud.mapper.UserMapper;
import cn.wolfcode.shop.cloud.redis.key.UserRedisKey;
import cn.wolfcode.shop.cloud.service.IUserService;
import cn.wolfcode.shop.cloud.common.AssertUtil;
import cn.wolfcode.shop.cloud.util.MD5Util;
import cn.wolfcode.shop.cloud.vo.LoginVo;
import cn.wolfcode.shop.cloud.web.msg.MemberServerCodeMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * Created by wolfcode-lanxw
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public User findById(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public String login(LoginVo vo) {
        // 2. 根据用户名查询用户, 判断用户名是否正确
        User user = userMapper.selectByPrimaryKey(Long.parseLong(vo.getMobile()));
        AssertUtil.notNull(user, MemberServerCodeMsg.USERNAME_OR_PASSWORD_ERROR);
        // 3. 比较用户密码是否一致, 需要对前端密码再次进行加密(formPass2DbPass)
        String inputPass = MD5Util.formPass2DbPass(vo.getPassword(), user.getSalt());
        AssertUtil.isEquals(user.getPassword(), inputPass, MemberServerCodeMsg.USERNAME_OR_PASSWORD_ERROR);
        // 4. 生成 token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        // 5. 以 token 作为 key,将当前用户保存到 redis 中
        redisTemplate.opsForValue().set(
                UserRedisKey.USER_TOKEN.join(token),
                JSONUtil.toJSONString(user),
                UserRedisKey.USER_TOKEN.getExpireTime(),
                UserRedisKey.USER_TOKEN.getUnit());
        return token;
    }

    @Override
    public Boolean refreshToken(String token) {
        return redisTemplate.expire(
                UserRedisKey.USER_TOKEN.join(token),
                UserRedisKey.USER_TOKEN.getExpireTime(),
                UserRedisKey.USER_TOKEN.getUnit());
    }

    @Override
    public User findByToken(String token) {
        String json = redisTemplate.opsForValue().get(UserRedisKey.USER_TOKEN.join(token));
        return JSONUtil.parseObject(json, User.class);
    }
}
